#include <signal.h>
#include <errno.h>
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
static void
tstpHandler (int sig)
{
  sigset_t tstpMask, prevMask;
  int savedErrno;
  struct sigaction sa;

  savedErrno = errno;

  sigemptyset (&tstpMask);
  sigaddset (&tstpMask, SIGTSTP);
  if (sigprocmask (SIG_UNBLOCK, &tstpMask, &prevMask) == -1)
    perror ("sigprocmask");

  printf ("Caught SIGTSTP\n");

  if (signal (SIGTSTP, SIG_DFL) == SIG_ERR)
    perror ("signal");

  raise (SIGTSTP);

/* Execution resumes here after SIGCONT */
  if (sigprocmask (SIG_SETMASK, &prevMask, NULL) == -1)
    perror ("sigprocmask");

  /* Reblock SIGTSTP */
  sigemptyset (&sa.sa_mask);

  /* Reestablish handler */
  sa.sa_flags = SA_RESTART;
  sa.sa_handler = tstpHandler;
  sa.sa_handler = tstpHandler;

  if (sigaction (SIGTSTP, &sa, NULL) == -1)
    perror ("sigaction");

  printf ("Exiting SIGTSTP handler\n");
  errno = savedErrno;
}

int
main (int argc, char *argv[])
{
  struct sigaction sa;

  if (sigaction (SIGTSTP, NULL, &sa) == -1)
    perror ("sigaction");

  if (sa.sa_handler != SIG_IGN)
     {
      sigemptyset (&sa.sa_mask);
      sa.sa_flags = SA_RESTART;
      sa.sa_handler = tstpHandler;
      if (sigaction (SIGTSTP, &sa, NULL) == -1)
	  perror ("sigaction");
    }
  for (;;)
    {
      pause ();
      printf ("Main\n");
    }
}
